package com.dingup.api.Util;

import com.suyeer.basic.util.BLogUtil;
import com.suyeer.cache.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * Created by wancheng on 2018/8/23.
 */
public class VerifyCodeUtil extends RedisUtil {

    private static class LazyHolder {
        private static final VerifyCodeUtil ourInstance = new VerifyCodeUtil();
    }
    public static VerifyCodeUtil getInstance() {
        return VerifyCodeUtil.LazyHolder.ourInstance;
    }

    private VerifyCodeUtil() {
    }

    private Logger logger = Logger.getLogger(VerifyCodeUtil.class);

    private final Integer CODE_EXIST_TIME = 60 * 3;

    private final Integer USER_CODE_MAP_EXIST_TIME = 60 * 15;

    private final String USER_HASH_KEY = "VERIFY_CODE_HASH_";

    private final String CODE_KEY = "VERIFY_CODE_";

    private final String SEND_NUMBER = "send_number";

    private final String CREATE_TIME = "create_time";

    private final Integer MAX_SEND_NUMBER = 2;

    private final String SEND_TIME_BEGIN_NUMBER = "1";

    private String getHashKey(String account){
        return USER_HASH_KEY + account;
    }
    private String getCodeKey(String acccount){
        return CODE_KEY + acccount;
    }

    public void putCode(String account,String code) throws Exception {
        if(get(getHashKey(account)) != null){
            Integer times = Integer.valueOf(get(getHashKey(account)));
            if(times > MAX_SEND_NUMBER){
                throw new Exception("15分钟内最多发送次数为2次");
            }else{
                Long seconds = ttl(getHashKey(account));
                set(getHashKey(account),String.valueOf(times + 1),Integer.valueOf(String.valueOf(seconds)));
            }
        }else{
            set(getHashKey(account),SEND_TIME_BEGIN_NUMBER,USER_CODE_MAP_EXIST_TIME);
        }

        set(getCodeKey(account),code);
    }
    public Boolean checkCode(String account,String code) throws Exception {
        if (StringUtils.isEmpty(code)){
            throw new Exception("验证码为空");
        }
        Boolean res = false;
        String codeCache = get(getCodeKey(account));
        if(StringUtils.isEmpty(codeCache)){
            throw new Exception("验证码已过期或已失效");
        }else {
            if(codeCache.equals(code)){
                res = true;
            }
        }
        return  res;
    }

    public Boolean ifCouldSendCode(String account){
        Boolean res = false;
        if(get(getHashKey(account)) != null){
            Integer times = Integer.valueOf(get(getHashKey(account)));
            if(times <= MAX_SEND_NUMBER){
                res = true;
            }
        }else{
            res = true;
        }
        return res;
    }
}
